package token.mobileapp.utils;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.KeepAliveHttpsTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * User: KienCT
 * Date: 26/07/2011
 * Time: 14:09
 */
public class TestService {
    private static final String NAMESPACE = "http://servlet.web.sc.com";
    private static String URL = "https://" + Constants.NETWORK_IP + "/services/AuthenticatorService?wsdl";
    private static final String METHOD_NAME = "sayHelloWorldFrom";
    private static final String SOAP_ACTION = "http://servlet.web.sc.com/sayHelloWorldFrom";

    public static String callService() {
        allowAllSSL();

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        PropertyInfo propInfo = new PropertyInfo();
        propInfo.name = "from";
        propInfo.type = PropertyInfo.STRING_CLASS;
        propInfo.setValue("love");

        request.addProperty(propInfo);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);

        KeepAliveHttpsTransportSE keepAliveHttpsTransportSE = new KeepAliveHttpsTransportSE(Constants.NETWORK_IP, 8443, "/services/AuthenticatorService?wsdl", 10000);
        keepAliveHttpsTransportSE.debug = true;

        try {
            keepAliveHttpsTransportSE.call(SOAP_ACTION, envelope);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        try {
            SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
            return resultsRequestSOAP.toString();
        } catch (SoapFault soapFault) {
            soapFault.printStackTrace();
            System.out.println(keepAliveHttpsTransportSE.responseDump);
        }
        return null;
    }

    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        }};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static TrustManager[] trustManagers;

    public static class _FakeX509TrustManager implements
            javax.net.ssl.X509TrustManager {
        private static final X509Certificate[] _AcceptedIssuers =
                new X509Certificate[]{};

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public boolean isClientTrusted(X509Certificate[] chain) {
            return (true);
        }

        public boolean isServerTrusted(X509Certificate[] chain) {
            return (true);
        }

        public X509Certificate[] getAcceptedIssuers() {
            return (_AcceptedIssuers);
        }
    }

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new
                HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession
                            session) {
                        return true;
                    }
                });

        javax.net.ssl.SSLContext context = null;

        if (trustManagers == null) {
            trustManagers = new javax.net.ssl.TrustManager[]{new
                    _FakeX509TrustManager()};
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {

        } catch (KeyManagementException e) {

        }

        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    }

}
